pp108 : Using XPath API

Using XPath API

This topic describes the usage of XPath API(s).

XPath API(s) can be used in C or C++ or Java.

C or C++


Tthere is no automatic garbage collection in the native layer. Therefore, ensure that you free the memory after use.

IncludexmlLib.h. If you want a C++ specific style with overloaded functions then includeXPath_xsl_optional.h.

tHXmlDoc xmlDoc = (tHXmlDoc)malloc(sizeof(tXmlDoc)); xmlInitDoc(xmlDoc); tChar pErrorBuf[1024]; tHXmlNode pXmlNode = xmlReadFromFile(xmlDoc, (tChar *)"d:weather.xml", pErrorBuf, 1024); /* Creating XPath */ tHXPath hXPath = xpathGetXPathInstance( "/weather/forecast/temperature[1]" ); tHXPathResult hXPathResult = 0; tHXPathNodeset hXPathNodeset = 0; tHXPathMetaInfo hMetaInfo = 0; if(hXPath) { /* Selecting NOM nodes */ hXPathNodeset = xpathSelectNodes(hXPath , pXmlNode, hMetaInfo); /* You can also use the more generic form - xpathValueOf() methods, */ deleteXPathNodesetInstance(hXPathNodeset); deleteXPathInstance(hXPath); }

Java

In Java the usage is more less like C or C++. For more information, refer to SDK documentation.

Document oDocument = new Document(); int iXml; try { iXml = oDocument.load("weather.xml"); XPath oXPath0 = XPath.getXPathInstance("//root/table "); NodeSet oNodeset = oXPath0.selectNodeSet(iXml); oNodeset.delete(); oXPath0.delete(); } catch (XMLException e) { e.printStackTrace(); }

Related reference

Defining XPath Expressions
XPath Parser, XPath Object and XPath Output
Understanding XPath Expressions
Optimizing XPath Expression Usage

Related information

Overview of XPath